import { PlusOutlined } from '@ant-design/icons'
import {
  Row,
  Col,
  Flex,
  Typography,
  Button,
  Form,
  Input,
  Select,
  Table,
  DatePicker,
  TimePicker,
  Switch,
  Drawer,
  Modal,
  Divider,
  Radio,
  message
} from 'antd'
import React, { useState } from 'react'
import { useEffect } from 'react'
import {
  timedMsgListAPI,
  timedMsgTaskListAPI,
  timedMsgTaskAddAPI
} from '../service/message'
import { userGroupList } from '../service/user'
import MyCron from '../components/MyCron'

// const dayPickerStyle = {
//   position: 'relative',
//   '& .ant-picker-header': {
//     display: 'none'
//   },
//   '& .ant-picker-content': {
//     marginTop: '44px' // 年月选择器的高度，确保滚动到日选择器
//   }
// }

// const format = 'HH:mm'
// const { RangePicker } = DatePicker
export default function TouchTimedPush() {
  const [form] = Form.useForm()
  // 模态框
  const [modalOpen, setModalOpen] = useState(false)
  const [isOpen, setIsOpen] = useState(false)
  // 是否显示文本框
  const [isShow, setIsShow] = useState('0')
  // 保存选中日期
  const [date, setDate] = useState(0)
  // 保存id
  const [id, setId] = useState()
  // 判断编辑还是添加

  // 日期切换
  const handleChange = (date, dataString) => {
    console.log(date, dataString)
  }
  // 保存定时任务列表
  const [timedMsgList, setTimedMsgList] = useState([])
  // 保存页码
  const [pageNo, setPageNo] = useState(1)
  // 保存总页数
  const [totalPage, setTotalPage] = useState(1)
  // 保存人群
  const [userList, setUserList] = useState([])
  // 人群页码
  const [userPageNo, setUserPageNo] = useState(1)
  // 保存定时模板列表
  const [timedMsgTempList, setTimedMsgTempList] = useState([])
  // 保存选中的人群
  const [selectedPerson, setSelectedPerson] = useState([])
  // 最终保存的人群
  const [selectedConfirmPerson, setSelectedConfirmPerson] = useState([])

  // 保存选中的人群id
  const [selectedPersonId, setSelectedPersonId] = useState([])
  // 保存最终选中的人群id
  const [selectedConfirmPersonId, setSelectedConfirmPersonId] = useState([])
  const [n, setN] = useState(0)
  useEffect(() => {
    ;(async () => {
      // 获取定时任务
      const res = await timedMsgTaskListAPI({ pageNo, pageSize: 10 })
      console.log(res)
      setTimedMsgList(res.data.list)
    })()
    // 查询定时模板
    ;(async () => {
      const res = await timedMsgListAPI({ pageNo: 1, pageSize: 100 })
      console.log(res)
      // 保存定时模板
      setTimedMsgTempList(res.data)
    })()
  }, [pageNo, n])
  useEffect(() => {
    ;(async () => {
      // 获取人群
      const res = await userGroupList({ pageNo: 1, pageSize: 1000 })
      console.log(res)
      if (res.data) {
        setUserList(res.data.objects)
      }
    })()
  }, [userPageNo])
  // 监听抽屉是否关闭
  useEffect(() => {
    if (!isOpen) {
      setSelectedPerson([])
      setSelectedConfirmPerson([])
      setSelectedPersonId('')
      setSelectedConfirmPersonId('')
    }
  }, [isOpen])

  return (
    <>
      <Row className="info">
        <Col span={24}>
          <Flex justify={'space-between'}>
            <Typography.Title level={3}>信息管理</Typography.Title>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => setIsOpen(true)}
            >
              新建推送任务
            </Button>
          </Flex>
        </Col>
      </Row>
      <Row className="container">
        <Col span={24}>
          <Form layout="inline">
            <Form.Item label="任务名称" name="storeName">
              <Input style={{ width: 200 }} />
            </Form.Item>
            <Form.Item label="启用状态" initialValue={'0'}>
              <Select
                style={{ width: 200 }}
                placeholder="请选择启用状态"
                options={[
                  {
                    value: '',
                    label: '全部'
                  },
                  {
                    value: '0',
                    label: '启用'
                  },
                  {
                    value: '1',
                    label: '停用'
                  }
                ]}
              />
            </Form.Item>
            <Form.Item>
              <Button type="default" htmlType="reset">
                重置
              </Button>
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
            </Form.Item>
          </Form>
        </Col>
      </Row>
      <Row className="container">
        <Col span={24}>
          <Typography.Paragraph style={{ fontSize: 16 }}>
            推送列表
          </Typography.Paragraph>
        </Col>
        <Col span={24}>
          <Table
            rowKey={(record) => record.id}
            dataSource={timedMsgList}
            pagination={{
              onChange: (page) => {
                setPageNo(page)
              },
              total: totalPage
            }}
            columns={[
              {
                title: '序号',
                dataIndex: 'id',
                key: 'id'
              },
              {
                title: '任务名称',
                dataIndex: 'jobDesc',
                key: 'jobDesc'
              },
              {
                title: 'Cron表达式',
                dataIndex: 'scheduleConf',
                key: 'scheduleConf'
              },
              {
                title: '推送状态',
                dataIndex: 'status',
                key: 'status',
                render: (_, record) => <>暂无</>
              },
              {
                title: '启用状态',
                dataIndex: 'creaeTime',
                key: 'creaeTime',
                render: (_, record) => (
                  <Switch
                    defaultChecked={record.triggerStatus === 1 ? true : false}
                  />
                )
              },
              {
                title: '操作',
                key: 'action',
                render: (_, record) => (
                  <span className="op">
                    <a
                      onClick={() => {
                        console.log(record)
                        setIsOpen(true)
                        // 给表单设置值
                        form.setFieldsValue(record)
                        // 保存id
                        setId(record.id)
                      }}
                    >
                      编辑
                    </a>
                    <a
                      onClick={async () => {
                        // const res = await triggerMsgDelAPI(record.id)
                        // console.log(res)
                        // if (res.code === '0') {
                        //   message.success('删除成功')
                        //   setN(n + 1)
                        // }
                      }}
                    >
                      删除
                    </a>
                  </span>
                )
              }
            ]}
          />
        </Col>
      </Row>
      {/* 右侧抽屉 */}
      <Drawer
        title="新建定时模板"
        onClose={() => {
          setIsOpen(false)
          setId()
        }}
        open={isOpen}
        width={500}
        maskClosable={false}
        destroyOnClose
      >
        <Form
          layout="vertical"
          preserve={false}
          form={form}
          onFinish={async (value) => {
            value.userList = selectedConfirmPersonId
            delete value.fa
            console.log(value)
            // 添加定时任务
            if (!id) {
              const res = await timedMsgTaskAddAPI(value)
              console.log(res)
              if (res.code === '0') {
                message.success('添加成功')
                setIsOpen(false)
                setN(n + 1)
              }
            }
          }}
        >
          <Form.Item
            label="任务名称"
            name="taskName"
            rules={[
              {
                required: true,
                message: '请输入任务名称'
              }
            ]}
          >
            <Input placeholder="请输入任务名称" />
          </Form.Item>
          <Form.Item
            label="请选择模板"
            name="tempId"
            rules={[
              {
                required: true,
                message: '请选择模板'
              }
            ]}
          >
            <Select
              placeholder="请选择模板"
              options={timedMsgTempList}
              fieldNames={{ label: 'tempName', value: 'id' }}
              onChange={(value, option) => {
                console.log(option)
                // 如果有多个
                if (option.targetCustomer.includes(',')) {
                  const arr = option.targetCustomer.split(',').map((item) => {
                    return Number(item)
                  })
                  console.log(arr)
                  setSelectedPersonId(arr)
                } else {
                  const id = Number(option.targetCustomer)
                  console.log(id)
                  setSelectedPersonId([id])
                }
              }}
            />
          </Form.Item>
          <Form.Item label="发送目标">
            <Row>
              <Col span={24}>
                <Button
                  type="primary"
                  onClick={() => {
                    // 深拷贝userList
                    const newUserList = [...userList]
                    let sortedUserList = []

                    // 首先添加selectedPersonId中的用户到sortedUserList的前端
                    selectedPersonId.forEach((id) => {
                      newUserList.forEach((user) => {
                        if (user.id === id) {
                          sortedUserList.push(user) // 将匹配的用户添加到sortedUserList
                        }
                      })
                    })

                    // 然后添加newUserList中不在selectedPersonId中的用户
                    newUserList.forEach((user) => {
                      if (!selectedPersonId.includes(user.id)) {
                        sortedUserList.push(user) // 将不匹配的用户添加到sortedUserList
                      }
                    })

                    setUserList(sortedUserList)
                    setModalOpen(true)
                  }}
                >
                  指定人群
                </Button>
                <span style={{ marginLeft: 10 }}>
                  {selectedConfirmPerson.join(',')}
                </span>
              </Col>
            </Row>
          </Form.Item>
          {/* <Form.Item label="发送方式" name="fa" initialValue={'0'}>
            <Radio.Group onChange={(e) => setIsShow(e.target.value)}>
              <Radio value="0">单次发送</Radio>
              <Radio value="1">周期性发送</Radio>
            </Radio.Group>
          </Form.Item> */}
          <>
            <Form.Item
              label="执行时间"
              name="cron"
              rules={[
                {
                  required: true,
                  message: '请输入cron表达式'
                }
              ]}
            >
              <Input placeholder="请提供cron表达式" />
            </Form.Item>
            <MyCron form={form} />
          </>
          {/* <Form.Item>
            {isShow === '0' ? (
              <DatePicker
                onChange={handleChange}
                showTime
                needConfirm={false}
                style={{ width: '100%' }}
              />
            ) : (
              <>
                <Form.Item label="执行时间" name="cron" rules={[
                  {
                    required: true,
                    message: '请输入cron表达式'
                  }
                ]}>
                  <Input placeholder="请提供cron表达式" />
                </Form.Item>
                <MyCron form={form} />
              </>
            )}
          </Form.Item> */}
          <Form.Item style={{ marginTop: 20, textAlign: 'right' }}>
            <Button type="primary" htmlType="submit">
              确定
            </Button>
          </Form.Item>
        </Form>
      </Drawer>
      {/* 选择营销活动 */}
      <Modal
        title="选择人群"
        open={modalOpen}
        width={1000}
        onCancel={() => setModalOpen(false)}
        onOk={() => {
          console.log(selectedPerson)
          // 如果selectedConfirmPerson为空数组，通过selectedPersonId到userList中获取对应的用户组名称，并放入到selectedConfirmPerson
          if (selectedPerson.length === 0) {
            const arr = []
            // 遍历selectedPersonId，如果包含在userList中，则将userList中对应的groupName放入到selectedPerson
            selectedPersonId.forEach((item) => {
              userList.forEach((user) => {
                if (item === user.id) {
                  arr.push(user.groupName)
                }
              })
            })
            console.log(arr)
            setSelectedConfirmPerson(arr)
          } else {
            setSelectedConfirmPerson(selectedPerson)
          }

          setSelectedConfirmPersonId(selectedPersonId)
          // setSelectedConfirmPerson(selectedPerson)

          // 关闭模态框
          setModalOpen(false)
        }}
        destroyOnClose
        maskClosable={false}
      >
        <Divider />
        <Row>
          <Col span={24}>
            <Form onFinish={() => {}} layout="inline">
              <Form.Item name="couponName" label="人群名称">
                <Input placeholder="请输入人群名称" />
              </Form.Item>
              <Form.Item>
                <Button type="primary" htmlType="submit">
                  查询
                </Button>
              </Form.Item>
            </Form>
          </Col>
        </Row>
        <Row style={{ marginTop: 20 }}>
          <Col span={24}>
            <Table
              rowKey="id"
              // 打开模态框框，设置默认选中人群

              rowSelection={{
                type: 'checkbox',
                selectedRowKeys: selectedPersonId,
                // 获取选中的
                onChange: (selectedRowKeys, selectedRows) => {
                  console.log(selectedRowKeys, selectedRows)
                  // 如果selectedPerson为空数组，通过selectedPersonId查找对应的人群名称并放入到数组
                  // 将groupName放到数组中
                  const selectedRowsName = selectedRows.map(
                    (item) => item.groupName
                  )
                  setSelectedPerson(selectedRowsName)
                  setSelectedPersonId(selectedRowKeys)
                }
              }}
              dataSource={userList}
              columns={[
                { key: 'id', title: '序号', dataIndex: 'id' },
                { key: 'groupName', title: '人群名称', dataIndex: 'groupName' },
                { key: 'desc', title: '人群描述', dataIndex: 'desc' },
                {
                  key: 'userNumber',
                  title: '用户数量',
                  dataIndex: 'userNumber'
                }
              ]}
              pagination={{
                pageSize: 5
              }}
            />
          </Col>
        </Row>
      </Modal>
    </>
  )
}
